Skip to main content

Array find

In the previous lesson, we learned about the Array .filter() method. In this lesson, we'll look at the .find() method, which is similar in its operation.

Let's start with an example, this time with a string array:

let words = ["javascript", "css", "html"];

let result = words.find(function (word) {
return word === "html";
});
console.log(result); // "html"

When you use the .find(callback) method on an array, you'll get the first item that matches the condition you specify. If no items were found, the result will be undefined.

The condition here is that the name must be equal to "html".

As a result, the.find(callback) method will execute the callback you specified for each item in the array until one of the callbacks returns true. When this happens, it stops calling the remaining callbacks and returns the item for which the callback returned true to you.

Here's the callback from our previous example:

function(word) {
return word === "html";
}

Let's take another example but this time with an array of numbers:

let numbers = [10, 4, 3, 15, 20, 2, 35];

let firstNumberAboveTen = numbers.find(function (number) {
return number > 10;
});
console.log(firstNumberAboveTen); // 4

Even though there are two numbers that satisfy the condition, the .find() method only returns the first one that does.

.filter() vs .find()

The distinction between these two methods is due to the return type:

  • The .filter() method always returns an array.
  • The .find() method returns the first array item that matches the callback function or undefined.

Let's look at some examples:

let ages = [10, 45, 19, 5, 34, 27, 13];

// filter() always returns an array
ages.filter(function (age) {
return age >= 18;
}); // [45, 19, 34, 27]

// .find() returns the first match or undefined
numbers.find(function (number) {
return number >= 18;
}); // 45
Note

Even if there is only one item that matches your condition, .filter() returns an array. The .find() method, on the other hand, will return the first item that matches the condition.

Now consider an example in which no items satisfy the condition:

let ages = [10, 45, 19, 34, 27, 13];

// filter() ALWAYS returns an array (even if it's empty)
ages.filter(function (age) {
return number < 10;
}); // []

// .find() returns the first match or undefined (when none of the items satisfy the condition)
ages.find(function (age) {
return number < 10>;
}); // undefined
Note

Take note of how the .filter() function returned an empty array and the .find() function returned undefined.

.find(callback) may return an undefined value. If you end up calling a method on its result, you may need to wrap it in an if condition to avoid unexpected errors.